package org.sample.springbootasync.log;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

@ControllerAdvice
@ConditionalOnProperty(name = "api.log", havingValue = "true")
public class RequestBodyLogger extends RequestBodyAdviceAdapter {

	private static final Logger LOGGER = LoggerFactory.getLogger(RequestBodyLogger.class);

	@Override
	public boolean supports(MethodParameter methodParameter, Type targetType,
			Class<? extends HttpMessageConverter<?>> converterType) {
		RequestMapping isHTTPRequest = methodParameter.getMethodAnnotation(RequestMapping.class);
		return isHTTPRequest != null;
	}

	@Override
	public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType,
			Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
		byte[] body = IOUtils.toByteArray(inputMessage.getBody());
		SimpleHttpInputMessage simpleHttpInputMessage = new SimpleHttpInputMessage(inputMessage.getHeaders(),
				new ByteArrayInputStream(body));
		String strBody = new String(body, StandardCharsets.UTF_8);
		LOGGER.info("HTTP request of {}.{}, type {}, parameter {}", parameter.getMethod().getDeclaringClass().getName(),
				parameter.getMethod().getName(), targetType.getTypeName(), parameter.getParameterName());
		LOGGER.info(strBody);
		return simpleHttpInputMessage;
	}
	
	@Override
	public Object handleEmptyBody(@Nullable Object body, HttpInputMessage inputMessage,
			MethodParameter parameter, Type targetType,
			Class<? extends HttpMessageConverter<?>> converterType) {

		LOGGER.info("HTTP request of {}.{}, type {}, parameter {}", parameter.getMethod().getDeclaringClass().getName(),
				parameter.getMethod().getName(), targetType.getTypeName(), parameter.getParameterName());
		return body;
	}

	class SimpleHttpInputMessage implements HttpInputMessage {
		private InputStream inputStream;
		private HttpHeaders httpHeaders;

		SimpleHttpInputMessage(HttpHeaders httpHeaders, InputStream inputStream) {
			this.inputStream = inputStream;
			this.httpHeaders = httpHeaders;
		}

		@Override
		public HttpHeaders getHeaders() {
			return httpHeaders;
		}

		@Override
		public InputStream getBody() throws IOException {
			return inputStream;
		}
	}

}
